package com.scitc.pleasurevideo.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;

import com.scitc.pleasurevideo.R;
import com.scitc.pleasurevideo.helper.ForwardHelper;
import com.scitc.pleasurevideo.imgutil.ImageManager;
import com.scitc.pleasurevideo.pojo.DoubanTvVo;

import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;


class HomeTopViewPage extends PagerAdapter {

    private List<DoubanTvVo> news;

    private Map newsView = new WeakHashMap();

    private Context context;

    public HomeTopViewPage(Context context, List<DoubanTvVo> news) {
        super();
        this.news = news;
        this.context = context;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;// 每次都强制刷新数据
    }

    @Override
    public int getCount() {
        if (news == null || news.size() < 1) {
            return 0;
        }
        return news.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (position >= news.size() || position < 0) {
            return;
        }
        final DoubanTvVo n = news.get(position);
        View view = (View) newsView.get(n.getId());
        container.removeView(view);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        final DoubanTvVo n = news.get(position);
        View view = (View) newsView.get(n.getId());
        if (view == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            view = layoutInflater.inflate(R.layout.top_index_head, container, false);
            newsView.put(n.getId(), view);
        }

        TextView title = (TextView) view.findViewById(R.id.title);
        ImageView mainimage = (ImageView) view.findViewById(R.id.mainimage);
        if (title != null) {
            title.setText(n.getTitle());
        }

        if (mainimage != null) {
            if (!TextUtils.isEmpty(n.getCover()) && n.getCover().length() > 4) {
                ImageManager.bindRoundedCornersImageCenterCrop(context, mainimage, n.getCover(), 1);
            } else {
                ImageManager.bindRoundedCornersImageCenterCrop(context, mainimage, "http://ads.tatatimes.com/test/shaoer.jpg", 1);
            }
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ForwardHelper.toTvMenuContentActivity((Activity) context, n);
            }
        });
        container.removeView(view);
        container.addView(view);
        return view;
    }

}